package com.funeral.api.aliyun.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.funeral.api.aliyun.po.AliyunConfigure;
import com.funeral.exception.CallException;

public class AliyunSMS {

    public static void sendMessage(String signName,String tempateCode,String phoneNumber,String jsonMsg)throws CallException{
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setMethod(MethodType.POST);
        smsRequest.setPhoneNumbers(phoneNumber);
        smsRequest.setTemplateCode(tempateCode);
        smsRequest.setSignName(signName);
        smsRequest.setTemplateParam(jsonMsg);

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunConfigure.ACCESSKEY_ID, AliyunConfigure.ACCESSKEY_SECRET);
        SendSmsResponse sendSmsResponse = null;
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", AliyunConfigure.SMS_PRODUCT, AliyunConfigure.SMS_DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            sendSmsResponse = acsClient.getAcsResponse(smsRequest);
        } catch (ClientException e) {
            throw new CallException(e);
        }
        if(!"OK".equals(sendSmsResponse.getCode())){
            try {
                System.out.println(new ObjectMapper().writeValueAsString(sendSmsResponse));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            throw new CallException("SMS Send Message faild!");
        }


    }
}
